package com.cc.moxingvoice.lock;

import android.content.Context;
import android.content.Intent;
import android.databinding.ViewDataBinding;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.cc.moxingvoice.BR;
import com.cc.moxingvoice.R;
import com.cc.moxingvoice.base.BaseLock;
import com.cc.moxingvoice.constant.Connection;
import com.cc.moxingvoice.constant.LocalPath;
import com.cc.moxingvoice.constant.MyUrl;
import com.cc.moxingvoice.databinding.FragmentVoicePackageBinding;
import com.cc.moxingvoice.model.VoicePackageItem;
import com.cc.moxingvoice.response.AdResponse;
import com.cc.moxingvoice.response.BannerResponse;
import com.cc.moxingvoice.response.GetUrlResponse;
import com.cc.moxingvoice.ui.main.MainActivity;
import com.cc.moxingvoice.ui.main.VoicePackageAdapter;
import com.cc.moxingvoice.ui.other.DonationActivity;
import com.cc.moxingvoice.ui.other.WebActivity;
import com.cc.moxingvoice.ui.voice.AddVoicePackageActivity;
import com.cc.moxingvoice.ui.voice.VoiceActivity;
import com.cc.moxingvoice.utils.FilesUtil;
import com.superc.cframework.base.ui.CBaseRecyclerViewAdapter;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import cn.bingoogolapple.bgabanner.BGABanner;

/**
 * 创建日期：2018/3/17 on 14:58
 * 描述：
 * 作者：郭士超
 * QQ：1169380200
 */

public class VoicePackageLock extends BaseLock<FragmentVoicePackageBinding> {

    private List<VoicePackageItem> mList;
    private VoicePackageAdapter mAdapter;

    private List<BannerResponse.DataBean> mBannerList;

    private boolean flagManage;

    private String QQqun;

    public VoicePackageLock(Context context, FragmentVoicePackageBinding binding) {
        super(context, binding);
    }

    public VoicePackageLock(Context context, FragmentVoicePackageBinding binding, Bundle bundle) {
        super(context, binding, bundle);
    }

    @Override
    protected void init() {
//        getNotice();
//        getAd();
        initList();
        initBanner();
        getBanner();
        getNotice();

    }

    private void initBanner() {
        mBinding.banner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
            @Override
            public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                RequestOptions options = new RequestOptions()
                        .centerCrop()
                        .placeholder(R.drawable.liyunlong)
                        .error(R.drawable.liyunlong)
                        .priority(Priority.HIGH)
                        .diskCacheStrategy(DiskCacheStrategy.NONE);

                Glide.with(getContext())
                        .applyDefaultRequestOptions(options)
                        .load(model)
                        .into(itemView);
            }
        });
        mBinding.banner.setDelegate(new BGABanner.Delegate<ImageView, String>() {
            @Override
            public void onBannerItemClick(BGABanner banner, ImageView itemView, String model, int position) {
                switch (mBannerList.get(position).getType()) {
                    case 0:
                        // 无操作
                        break;
                    case 1:
                        startWebActivity(mBannerList.get(position).getContent());
                        break;
                    case 2:
                        joinQQGroup(mBannerList.get(position).getContent());
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void startWebActivity(String url){
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        startActivity(WebActivity.class, bundle);
    }

    /****************
     *
     * 发起添加群流程。群号：魔性语音包-群1(104795047) 的 key 为： A-KvX-4cpiKOou12d2qw6s4JZ_e97s7O
     * 调用 joinQQGroup(A-KvX-4cpiKOou12d2qw6s4JZ_e97s7O) 即可发起手Q客户端申请加群 魔性语音包-群1(104795047)
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回fals表示呼起失败
     ******************/
    private boolean joinQQGroup(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }


    public void refreshList() {
        flagManage = false;
        addList();
    }

    private void addList() {
        mList.clear();

        Drawable add = getContext().getResources().getDrawable(R.drawable.add_voice_package);
        mList.add(new VoicePackageItem("", add, "点我添加本地语音包\n或点击软件下方发现获取更多网络语音包", false));

        List<String> voicePackageList = FilesUtil.getFolderName(LocalPath.VOICE_PATH);
        int id = 0;
        for (String voicePackage : voicePackageList) {
            id++;
            try {
                String picPath = LocalPath.VOICE_PATH + voicePackage + "/" + LocalPath.VOICE_ICON;
                Drawable drawable;
                if (FilesUtil.isFileExists(picPath)) {
                    FileInputStream fis = new FileInputStream(picPath);
                    Bitmap bitmap = BitmapFactory.decodeStream(fis);
                    drawable = new BitmapDrawable(bitmap);
                } else {
                    drawable = getContext().getResources().getDrawable(R.drawable.icon);
                }
                mList.add(new VoicePackageItem(id + "", drawable, voicePackage, true));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        mAdapter.notifyDataSetChanged(); // 刷新数据
    }

    private void initList() {
        mList = new ArrayList<VoicePackageItem>();
        LinearLayoutManager ms = new GridLayoutManager(mContext, 2);
        mBinding.rvVoicePackage.setLayoutManager(ms);
        mAdapter = new VoicePackageAdapter(mContext, mList, R.layout.item_voice_package, BR.item);
        mBinding.rvVoicePackage.setAdapter(mAdapter); // 这里或者在xml里设置adapter
        mAdapter.setOnItemClickListener(new CBaseRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ViewDataBinding binding, int position) {
                if (position == 0) {
                    startActivity(AddVoicePackageActivity.class);
                    return;
                }

                Bundle bundle = new Bundle();
                bundle.putString("title", mList.get(position).getTitle());
                bundle.putBoolean("manage", true);
                startActivity(VoiceActivity.class, bundle);
            }
        });
    }

    public boolean appBarRightManage() {
        flagManage = !flagManage;
        for (VoicePackageItem item : mList) {
            if (!item.isModifiable()) {
                continue;
            }
            item.setManage(flagManage);
            item.notifyChange();
        }
        return flagManage;
    }

    public void donation() {
        startActivity(DonationActivity.class);
    }

    public CBaseRecyclerViewAdapter getAdapter() {
        return mAdapter;
    }

    private void getBanner() {
        mBinding.banner.setVisibility(View.GONE);
        // 访问网络的方法
        HashMap hashMap = new HashMap();
        Connection.getInstance().post(BannerResponse.class, MyUrl.GET_BANNER, hashMap, new Connection.ResponseListener() {
            @Override
            public void tryReturn(int id, Object response) {
                final BannerResponse result = (BannerResponse) response;
                switch (id) {
                    case 200:
                        mBinding.banner.setVisibility(View.VISIBLE);
                        mBinding.tvNotice.setVisibility(View.GONE);
                        mBannerList = result.getData();
                        List<String> imgUrlList = new ArrayList<>();
                        List<String> titleList = new ArrayList<>();
                        for (BannerResponse.DataBean item : mBannerList) {
                            imgUrlList.add(item.getImg_url());
                            titleList.add("");
                        }
                        mBinding.banner.setData(imgUrlList, titleList);
                        break;
                    case -2:

                        break;
                    default:

                        break;
                }
            }
        });
    }

    private void getNotice() {
//        mBinding.tvNotice.setText("祝大家：大吉大利，今晚吃鸡。\n加QQ群：104795984    解决使用不正常情况。");

        // 访问网络的方法
        HashMap hashMap = new HashMap();
        Connection.getInstance().post(GetUrlResponse.class, MyUrl.GET_NOTICE, hashMap, new Connection.ResponseListener() {
            @Override
            public void tryReturn(int id, Object response) {
                final GetUrlResponse result = (GetUrlResponse) response;
                switch (id) {
                    case 200:
                        mBinding.tvNotice.setText(result.getData().getText());
                        if (result.getData().getUrl() == null || result.getData().getUrl().isEmpty()) {
                            return;
                        }
                        mBinding.tvNotice.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Bundle bundle = new Bundle();
                                bundle.putString("url", result.getData().getUrl());
                                startActivity(WebActivity.class, bundle);
                            }
                        });
                        break;
                    case -2:

                        break;
                    default:

                        break;
                }
            }
        });
    }

    private void getAd() {
        // 访问网络的方法
        HashMap hashMap = new HashMap();
        Connection.getInstance().post(AdResponse.class, MyUrl.GET_AD, hashMap, new Connection.ResponseListener() {
            @Override
            public void tryReturn(int id, Object response) {
                final AdResponse result = (AdResponse) response;
                switch (id) {
                    case 200:
                        mBinding.tvAd.setText(result.getData().getText());
                        mBinding.tvAd.setVisibility(View.VISIBLE);
                        mBinding.tvAd.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(result.getData().getUrl());
                                intent.setData(content_url);
                                startActivity(intent);
                            }
                        });
                        break;
                    case -2:
                        mBinding.tvAd.setVisibility(View.GONE);
                        break;
                    default:
                        mBinding.tvAd.setVisibility(View.GONE);
                        break;
                }
            }
        });
    }


}
